package main

import (
	"fmt"
	"net/http"
	"os"
	"playbook/ginsvr/src/api"
	"strings"

	"playbook/ginsvr/src/orm/atomservice"
	"playbook/ginsvr/src/projectmanagement"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"

	"playbook/ginsvr/src/file/upload"
	"playbook/ginsvr/src/orm"
	"playbook/ginsvr/src/source/read"
	"playbook/ginsvr/src/utils/fileutil"
	"playbook/ginsvr/src/utils/fileutil/watcher"
	"playbook/ginsvr/src/utils/httputil"
	"playbook/ginsvr/src/utils/netutil"

	"playbook/ginsvr/src/atom"
	"playbook/ginsvr/src/config"
	"playbook/ginsvr/src/errno"
	"playbook/ginsvr/src/global"
	"playbook/ginsvr/src/parsejson"
	"playbook/ginsvr/src/source/gene"
)

func logInit(file *os.File) {

	global.LOG.Out = file

	global.LOG.Formatter = &logrus.JSONFormatter{}
}

func main() {

	file, err := os.OpenFile("./playbook.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		panic(err)
	}
	logInit(file)

	defer file.Close()
	defer watcher.Watcher.Close()

	//read.GetAtomSvrLst()
	//read.AtomParseByPath()
	//gene.GeneParamBean("composebean", "testcomp", "1bac55abe93843cab8f38a8ce20bef1f")

	// watcher.Watcher.Add("C:\\Users\\wzz\\Documents\\工作\\test\\watcher1")

	// watcher.Watcher.Add("C:\\Users\\wzz\\Documents\\工作\\test\\watcher2")

	r := setupPlaybook()
	// Listen and Server in 0.0.0.0:8080
	r.Run(":8080")
}

func cors() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method

		context.Header("Access-Control-Allow-Origin", "*")
		context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, x-token")
		context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PATCH, PUT")
		context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, multipart/form-data")
		context.Header("Access-Control-Allow-Credentials", "true")

		if method == "OPTIONS" {
			context.AbortWithStatus(http.StatusNoContent)
		}
	}
}

func setupPlaybook() *gin.Engine {

	r := gin.Default()
	r.Use(cors())

	r.POST("getProcess", func(c *gin.Context) {
		// Parse JSON
		var json struct {
			ProcessName string `json:"processName" binding:"required"`
		}

		if c.Bind(&json) == nil {
			pro := orm.GetProcess(json.ProcessName)
			c.JSON(http.StatusOK, pro)
		}
	})

	r.POST("getSubProcess", func(c *gin.Context) {
		// Parse JSON
		var json struct {
			ProcessName string `json:"processName" binding:"required"`
		}

		if c.Bind(&json) == nil {
			pro := orm.GetSubProcess(json.ProcessName)
			c.JSON(http.StatusOK, pro)
		}
	})

	r.POST("getAllActivity", func(c *gin.Context) {
		// Parse JSON
		pro := orm.GetAllActivity()
		c.JSON(http.StatusOK, pro)
	})

	r.GET("attach", func(c *gin.Context) {
		// var str string = "Hello World"
		// c.JSON(http.StatusOK, str)
		pro := orm.Attach()
		c.JSON(http.StatusOK, pro)
	})

	r.GET("getVersionConfig", func(c *gin.Context) {
		pro := config.GetVersionConfig()
		c.JSON(http.StatusOK, pro)
	})

	r.POST("getLocalPath", func(c *gin.Context) {
		var userInfo struct {
			UserId string `json:"userId" binding:"required"`
		}
		if c.Bind(&userInfo) == nil {
			fmt.Println(userInfo)
			pro := orm.GetLocalPath(userInfo.UserId)
			c.JSON(http.StatusOK, pro)
		} else {
			fmt.Println("add local path err.")
		}
	})

	r.POST("addLocalPath", func(c *gin.Context) {
		var localPath struct {
			UserId    string `json:"userId" binding:"required"`
			LocalPath string `json:"localPath" binding:"required"`
		}
		if c.Bind(&localPath) == nil {
			fmt.Println(localPath)
			pro := orm.AddLocalPath(localPath.UserId, localPath.LocalPath)
			c.JSON(http.StatusOK, pro)
		}
	})

	r.POST("updateLocalPath", func(c *gin.Context) {
		var localPath struct {
			UserId    string `json:"userId" binding:"required"`
			LocalPath string `json:"localPath" binding:"required"`
		}
		if c.Bind(&localPath) == nil {
			fmt.Println(localPath)
			pro := orm.UpdateLocalPath(localPath.UserId, localPath.LocalPath)
			c.JSON(http.StatusOK, pro)
		}
	})

	//新增编排服务
	r.POST("addProcess", func(c *gin.Context) {
		var process orm.FullProcess
		if c.Bind(&process) == nil {
			pro := orm.AddProcess(process).(map[string]interface{})
			if pro["respCode"] == "000001" {
				c.JSON(http.StatusOK, pro)
				return
			}
			genebeanlist := pro["genebeanmsgList"].([]orm.GenebeanParammsg)

			for _, genebeanmsg := range genebeanlist {
				if genebeanmsg.Inparamid != "" {
					gene.GeneParamBean("composebean", pro["processname"].(string), genebeanmsg.Inparamid, genebeanmsg.Subpath)
				}
				if genebeanmsg.Outparamid != "" {
					gene.GeneParamBean("composebean", pro["processname"].(string), genebeanmsg.Outparamid, genebeanmsg.Subpath)
				}

			}
			var resp orm.Response
			resp.RespCode = "000000"
			resp.RespMsg = pro["processid"].(string)
			c.JSON(http.StatusOK, resp)
		}
	})

	//子流程新增
	r.POST("addSubProcess", func(c *gin.Context) {
		var subprocess orm.FullSubProcess
		if c.Bind(&subprocess) == nil {
			pro := orm.AddSubprocess(subprocess).(map[string]interface{})
			if pro["respCode"] == "000001" {
				c.JSON(http.StatusOK, pro)
				return
			}
			genebeanlist := pro["genebeanmsgList"].([]orm.GenebeanParammsg)

			for _, genebeanmsg := range genebeanlist {
				if genebeanmsg.Inparamid != "" {
					gene.GeneParamBean("composebean", pro["processname"].(string), genebeanmsg.Inparamid, genebeanmsg.Subpath)
				}
				if genebeanmsg.Outparamid != "" {
					gene.GeneParamBean("composebean", pro["processname"].(string), genebeanmsg.Outparamid, genebeanmsg.Subpath)
				}
			}
			var resp orm.Response
			resp.RespCode = "000000"
			resp.RespMsg = pro["processid"].(string)
			c.JSON(http.StatusOK, resp)
		}
	})

	//编排服务更新
	r.POST("updateProcess", func(c *gin.Context) {
		var process orm.FullProcess
		if c.Bind(&process) == nil {
			var resp orm.Response
			if process.Process.Name == "" {
				resp.RespCode = "000002"
				resp.RespMsg = "process name can not be null!"
				c.JSON(http.StatusOK, resp)
				return
			}

			pro := orm.UpdateProcess(process).(map[string]interface{})
			if pro["respCode"] == "000001" {
				c.JSON(http.StatusOK, pro)
				return
			}
			genebeanlist := pro["genebeanmsgList"].([]orm.GenebeanParammsg)

			for _, genebeanmsg := range genebeanlist {
				if genebeanmsg.Inparamid != "" {
					gene.GeneParamBean("composebean", pro["processname"].(string), genebeanmsg.Inparamid, genebeanmsg.Subpath)
				}
				if genebeanmsg.Outparamid != "" {
					gene.GeneParamBean("composebean", pro["processname"].(string), genebeanmsg.Outparamid, genebeanmsg.Subpath)
				}

			}
			resp.RespCode = "000000"
			resp.RespMsg = "process update success!"
			c.JSON(http.StatusOK, resp)
		}
	})

	//子流程更新
	r.POST("updateSubProcess", func(c *gin.Context) {
		var process orm.FullSubProcess
		if c.Bind(&process) == nil {
			var resp orm.Response
			if process.SubProcess.Name == "" {
				resp.RespCode = "000002"
				resp.RespMsg = "process name can not be null!"
				c.JSON(http.StatusOK, resp)
				return
			}
			pro := orm.UpdateSubprocess(process).(map[string]interface{})
			if pro["respCode"] == "000001" {
				c.JSON(http.StatusOK, pro)
				return
			}
			genebeanlist := pro["genebeanmsgList"].([]orm.GenebeanParammsg)

			for _, genebeanmsg := range genebeanlist {
				if genebeanmsg.Inparamid != "" {
					gene.GeneParamBean("composebean", pro["processname"].(string), genebeanmsg.Inparamid, genebeanmsg.Subpath)
				}
				if genebeanmsg.Outparamid != "" {
					gene.GeneParamBean("composebean", pro["processname"].(string), genebeanmsg.Outparamid, genebeanmsg.Subpath)
				}

			}
			resp.RespCode = "000000"
			resp.RespMsg = "process update success!"
			c.JSON(http.StatusOK, resp)
		}
	})

	//子流程删除
	r.POST("deletesubprocess", func(c *gin.Context) {
		var processname struct {
			Name string `json:"processname"`
		}
		if c.Bind(&processname) == nil {
			var errpath []string
			var resp orm.Response

			subprocess := orm.GetProcessBasicInfoByName(processname.Name)
			projectpath := projectmanagement.GetProjectPathByIdFlag(subprocess.Projectid, "boot").(map[string]interface{})
			if projectpath["respCode"] != "000000" {
				c.JSON(http.StatusOK, projectpath)
				return
			}

			pro := orm.DeleteSubProcess(projectpath["projectpath"].(string), processname.Name)
			value, ok := pro.(map[string]interface{})
			if ok {
				c.JSON(http.StatusOK, value)
				return
			}

			for _, srcpath := range pro.([]string) {
				err := fileutil.DeleteFile(srcpath, false)
				if err != nil {
					errpath = append(errpath, srcpath)
				}
			}
			if len(errpath) != 0 {
				resp.RespCode = "000001"
				resp.RespMsg = "Failed to delete subprocess. Please delete the following folders manually：" + strings.Join(errpath, "")
				c.JSON(http.StatusOK, resp)
				return
			}
			//删除服务器上的子流程脚本服务信息
			publicpath := orm.GetLocalPath("public")
			srcpath := orm.GetGeneSrcDefine("script").Srcpath + global.PTHSEP + processname.Name
			err := httputil.FileDel(publicpath.LocalIp, srcpath)
			if err != nil {
				resp.RespCode = "000001"
				resp.RespMsg = "Failed to delete the server script files. Please contact the administrator to delete them"
				c.JSON(http.StatusOK, resp)
				return
			}
			resp.RespCode = "000000"
			resp.RespMsg = "subprocess delete success!"
			c.JSON(http.StatusOK, resp)
		}
	})

	//编排服务列表查询
	r.POST("getProcessLst", func(c *gin.Context) {
		var qrycondition struct {
			Name         string `json:"name"`
			Projectname  string `json:"projectname"`
			Issubprocess bool   `json:"issubprocess"`
			Pagenum      int    `json:"pagenum"`
			Pagesize     int    `json:"pagesize"`
		}
		if c.Bind(&qrycondition) == nil {
			pro := orm.GetProcessLst(qrycondition.Name, qrycondition.Projectname, qrycondition.Pagenum, qrycondition.Pagesize, qrycondition.Issubprocess)
			c.JSON(http.StatusOK, pro)
		}
	})

	r.POST("getAtomSvrDef", func(c *gin.Context) {
		var atomsvr orm.AtomSvrDefine
		if c.Bind(&atomsvr) == nil {
			pro := orm.GetAtomSvrDef(atomsvr)
			c.JSON(http.StatusOK, pro)
		}
	})

	//返回前端json文件
	r.POST("getProcessJson", func(c *gin.Context) {
		var processname struct {
			Name      string `json:"processname"`
			Projectid string `json:"projectid"`
		}
		if c.Bind(&processname) == nil {
			projectpath := projectmanagement.GetProjectPathByIdFlag(processname.Projectid, "boot").(map[string]interface{})
			if projectpath["respCode"] != "000000" {
				c.JSON(http.StatusOK, projectpath)
				return
			}
			pro := orm.GetProcessJson(processname.Name, projectpath["projectpath"].(string))
			c.JSON(http.StatusOK, pro)
		}
	})

	r.GET("getSrcPath", func(c *gin.Context) {
		srcpath := orm.GetSrcPath()
		c.JSON(http.StatusOK, srcpath)

	})

	r.POST("atomParseByPath", func(c *gin.Context) {
		read.AtomParseByPath()
		c.JSON(http.StatusOK, gin.H{"status": "complete"})
	})

	r.POST("getCatagory", func(c *gin.Context) {
		var srcata struct {
			Cgtype   string `json:"cgtype" binding:"required"`
			Parentid string `json:"parentid"`
		}
		if c.Bind(&srcata) == nil {
			pro := orm.GetCatagory(srcata.Cgtype, srcata.Parentid)
			c.JSON(http.StatusOK, pro)
		}
	})

	r.POST("getCatagoryTree", func(c *gin.Context) {
		var srcata struct {
			Cgtype   string `json:"cgtype" binding:"required"`
			Parentid string `json:"parentid"`
		}
		if c.Bind(&srcata) == nil {
			pro := orm.GetCatagoryTree(srcata.Cgtype, srcata.Parentid)
			c.JSON(http.StatusOK, pro)
		}
	})

	r.POST("getAtomParamList", func(c *gin.Context) {
		var paramid struct {
			Paramid string `json:"paramid" binding:"required"`
		}
		if c.Bind(&paramid) == nil {
			pro := orm.GetAtomParameterList(paramid.Paramid)
			c.JSON(http.StatusOK, pro)
		}
	})

	r.POST("processScan", func(c *gin.Context) {
		// var str string = "Hello World"
		// c.JSON(http.StatusOK, str)
		resp := read.Processscan()
		c.JSON(http.StatusOK, resp)
	})

	r.POST("clean", func(c *gin.Context) {
		// var str string = "Hello World"
		// c.JSON(http.StatusOK, str)
		resp := orm.CleanAll()
		c.JSON(http.StatusOK, resp)
	})

	r.POST("scriptGen", func(c *gin.Context) {
		var resp orm.Response
		var scriptdata httputil.Scriptdata

		var sgresp httputil.Sgresp

		if c.Bind(&scriptdata) == nil {
			scs, pcb, err := gene.GeneScriptStruct("script", *scriptdata.Act)
			if err != nil {
				resp.RespCode = "000001"
				resp.RespMsg = err.Error()
				c.JSON(http.StatusOK, resp)
				return
			}
			//watch script output bean，waiting for re-code
			watcher.AddWatchFile(pcb.Srcpath+global.PTHSEP+pcb.ParamBean.Name+".java", scriptdata.IP)
			gene.GeneScriptStruct("script", *scriptdata.Act)

			watcher.AddWatchFile(scs.SrcName, scriptdata.IP)
			sgresp.Srcpath = fileutil.GetAbsPath(scs.SrcName)
		}
		sgresp.Head.RespCode = "000000"
		sgresp.Head.RespMsg = "script gene success!"
		c.JSON(http.StatusOK, sgresp)
	})

	r.POST("scriptGenLocal", func(c *gin.Context) {
		var act orm.Activity
		var resp orm.Response
		var scriptdata httputil.Scriptdata

		if c.Bind(&act) == nil {
			ip, err := netutil.ExternalIP()
			if err != nil {
				global.LOG.WithFields(logrus.Fields{
					"err": err,
				}).Error("get local ip err.")

				resp.RespCode = "000001"
				resp.RespMsg = "script local gene fail!"
				c.JSON(http.StatusOK, resp)
				return
			}
			scriptdata.IP = ip.String()
			scriptdata.Act = &act
			srcpath, _ := httputil.PublicScriptCrt(scriptdata)

			var sgresp httputil.Sgresp
			sgresp.Head.RespCode = "000000"
			sgresp.Head.RespMsg = "script local gene succcess!"
			sgresp.Srcpath = fileutil.SepTransLux(srcpath)
			c.JSON(http.StatusOK, sgresp)
		}
	})

	r.POST("fileReWrite", func(c *gin.Context) {
		var srcfile httputil.Srcfile
		var resp orm.Response

		if c.Bind(&srcfile) == nil {
			//path := strings.Replace(srcfile.Srcpath, ".java", "", -1)
			path := srcfile.Srcpath
			if !fileutil.FileExist(path, false) {
				fileutil.GetClearFile(path, "")
			}
			fileutil.Filewrite(srcfile.Srcpath, srcfile.Flst)
		}

		resp.RespCode = "000000"
		resp.RespMsg = "script local write succcess!"
		c.JSON(http.StatusOK, resp)
	})

	r.POST("filedelete", func(c *gin.Context) {
		var srcfile httputil.Srcfile
		var resp orm.Response

		if c.Bind(&srcfile) == nil {
			fileutil.DeleteFile(srcfile.Srcpath, false)
		}

		resp.RespCode = "000000"
		resp.RespMsg = "script local delete succcess!"
		c.JSON(http.StatusOK, resp)
	})

	r.POST("saveProcess", func(c *gin.Context) {
		fmt.Println("saveProcess start")
		var cells parsejson.Cells
		if c.Bind(&cells) == nil {
			// var test []interface{}
			// json.Unmarshal(cells, &test)
			// fmt.Println(cells)
			var resp orm.Response
			if len(cells.Cells) == 0 {
				resp.RespCode = "000002"
				resp.RespMsg = "json can not be null!"
				c.JSON(http.StatusOK, resp)
				return
			}

			pro := parsejson.SaveProcess(cells.Cells).(map[string]interface{})
			if pro["respCode"] == "000001" || pro["respCode"] == "000003" {
				c.JSON(http.StatusOK, pro)
				return
			}

			resp.RespCode = "000000"
			resp.RespMsg = "process save success!"
			c.JSON(http.StatusOK, resp)
		}
	})
	r.POST("scan", func(c *gin.Context) {
		var resp orm.Response
		resp = orm.CleanAll()
		if resp.RespCode != "000000" {
			c.JSON(http.StatusExpectationFailed, resp)
			return
		}
		read.AtomParseByPath()
		resp = read.Processscan()
		if resp.RespCode != "000000" {
			c.JSON(http.StatusExpectationFailed, resp)
			return
		}
		resp.RespCode = "000000"
		resp.RespMsg = "scan succcess!"
		c.JSON(http.StatusOK, resp)
	})

	r.POST("download", func(c *gin.Context) {
		fmt.Println("saveProcess start")
		var cells parsejson.Cells
		if c.Bind(&cells) == nil {
			var resp orm.Response
			if len(cells.Cells) == 0 {
				resp.RespCode = "000002"
				resp.RespMsg = "json can not be null!"
				c.JSON(http.StatusOK, resp)
				return
			}

			pro := parsejson.DownloadJson(cells.Cells)
			c.JSON(http.StatusOK, pro)
		}
	})
	//数据字典根据名称查询
	r.POST("getParamByName", api.GetParamByName)
	r.POST("reverseJson", func(c *gin.Context) {
		fmt.Println("reverseJson start")
		var fullProcess parsejson.FullProcess
		if c.Bind(&fullProcess) == nil {
			var resp orm.Response
			process := fullProcess.Process
			if process.Name == "" {
				resp.RespCode = "000002"
				resp.RespMsg = "json can not be null!"
				c.JSON(http.StatusOK, resp)
				return
			}

			result := parsejson.SaveReverseJson(process)
			// resp.RespCode = "000000"
			// resp.RespMsg = "process reverse success!"
			c.JSON(http.StatusOK, result)
		}
	})

	//查询数据字典中的所有参数
	r.POST("getAllParamInDict", api.GetAllParamInDict)

	//添加查询数据字典
	r.POST("getParamInDictByCondiction", api.GetParamInDictByCondiction)
	//数据字典新增
	r.POST("addParamInDict", api.AddParamInDict)
	//数据字典根据id查询参数
	r.POST("getParamInDictById", api.GetParamInDictById)
	//数据字典更新
	r.POST("updateParamdef", api.UpdateParamdef)
	//数据字典删除
	r.POST("deleteParamdefById", api.DeleteParamdefById)

	// 生成表操作原子服务
	r.POST("addAtomSvr", func(c *gin.Context) {
		var atomParam atom.AtomParam
		errr := c.Bind(&atomParam)
		if errr != nil {
			logrus.Error(errr.Error())
		}
		err := atom.CreateAtomService(atomParam)
		if err != nil {
			c.JSON(http.StatusOK, errno.ErrAtomCreate().WithDetailMessage(err.Error()))
			c.Abort()
			return
		}
		c.JSON(http.StatusOK, errno.OK())

	})

	// 上传数据库脚本文件
	r.POST("uploadDbScript", func(c *gin.Context) {
		err := upload.UploadAndParsel(c)
		c.JSON(http.StatusOK, err)
	})

	// 查询所有表名
	r.POST("getTableNames", func(c *gin.Context) {
		var param map[string]interface{}
		if c.Bind(&param) == nil {
			resp := atom.GetTableNames(param["projectId"])
			c.JSON(http.StatusOK, errno.OK().WithData(resp))
		}
	})

	//查询表的字段名称
	r.POST("GetFeildNames", func(c *gin.Context) {
		var param map[string]string
		if c.Bind(&param) == nil {
			resp := atom.GetFeildNames(param["projectId"], param["tableName"])
			c.JSON(http.StatusOK, errno.OK().WithData(resp))
		}
	})

	r.POST("GetSqlKeywords", func(c *gin.Context) {
		resp := atom.GetSqlKeywords()
		c.JSON(http.StatusOK, errno.OK().WithData(resp))
	})

	// 提取sql中的要查询的字段名称
	r.POST("GetResultMap", func(c *gin.Context) {
		var param map[string]string
		if c.Bind(&param) == nil {
			resp := atom.GetResultMap(param["sql"])
			c.JSON(http.StatusOK, errno.OK().WithData(resp))
		}
	})

	/**
	*  子流程复制
	 */
	r.POST("copySubProcess", api.CopySubProcess)

	r.POST("scriptcopy", api.Scriptcopy)

	r.POST("saveSubProcess", api.SaveSubProcess)

	r.POST("getConfig", func(c *gin.Context) {
		var configtype struct {
			Configtype string `json:"configtype"`
		}
		if c.Bind(&configtype) == nil {
			resp := config.GetConfig(configtype.Configtype)
			c.JSON(http.StatusOK, resp)
		}
	})

	//新增原子服务
	r.POST("addAtomService", func(c *gin.Context) {
		var param map[string]interface{}
		if c.Bind(&param) == nil {
			resp := atomservice.AddAotm(param)
			c.JSON(http.StatusOK, resp)
		}
	})

	// 新增项目
	r.POST("addProject", func(c *gin.Context) {
		var project projectmanagement.FullProject
		var resp orm.Response
		if c.Bind(&project) == nil {
			pro, err := projectmanagement.AddProject(project)
			if err != nil {
				resp.RespCode = pro.RespCode
				resp.RespMsg = err.Error()
				c.JSON(http.StatusOK, resp)
				return
			}
			c.JSON(http.StatusOK, pro)
		}
	})

	// 通过项目id查询项目路径
	r.POST("getProjectPathById", func(c *gin.Context) {
		var param map[string]interface{}
		if c.Bind(&param) == nil {
			pro := projectmanagement.GetProjectPathById(param["projectid"].(string))
			c.JSON(http.StatusOK, pro)
		}
	})

	// 通过项目id和标识查询项目路径
	r.POST("getProjectPathByIdFlag", func(c *gin.Context) {
		var param map[string]interface{}
		if c.Bind(&param) == nil {
			pro := projectmanagement.GetProjectPathByIdFlag(param["projectid"].(string), param["flag"].(string))
			c.JSON(http.StatusOK, pro)
		}
	})

	// 查询项目列表
	r.POST("getProjectList", func(c *gin.Context) {
		var qrycondition struct {
			Projectname string `json:"projectname"`
			Pagenum     int    `json:"pagenum"`
			Pagesize    int    `json:"pagesize"`
		}
		if c.Bind(&qrycondition) == nil {
			pro := projectmanagement.GetProjectList(qrycondition.Projectname, qrycondition.Pagenum, qrycondition.Pagesize)
			c.JSON(http.StatusOK, pro)
		}
	})

	// 项目编辑
	r.POST("updateProject", func(c *gin.Context) {
		var project projectmanagement.FullProject
		var resp orm.Response
		if c.Bind(&project) == nil {
			if project.Project.Projectid == "" {
				resp.RespCode = "000002"
				resp.RespMsg = "projectid can not be null!"
				c.JSON(http.StatusOK, resp)
				return
			}
			if project.Project.Projectpath == "" {
				resp.RespCode = "000003"
				resp.RespMsg = "projectpath can not be null!"
				c.JSON(http.StatusOK, resp)
				return
			}
			if project.Project.Projectname == "" {
				resp.RespCode = "000004"
				resp.RespMsg = "projectname can not be null!"
				c.JSON(http.StatusOK, resp)
				return
			}
			pro, _ := projectmanagement.UpdateProject(project)
			if pro.RespCode == "000001" {
				c.JSON(http.StatusOK, pro)
				return
			}
			c.JSON(http.StatusOK, pro)
		}
	})

	// 新增项目推送到server端
	r.POST("projectGenLocal", func(c *gin.Context) {
		var project projectmanagement.FullProject
		var resp orm.Response
		var projectdata httputil.Projectdata

		if c.Bind(&project) == nil {
			ip, err := netutil.ExternalIP()
			if err != nil {
				global.LOG.WithFields(logrus.Fields{
					"err": err,
				}).Error("get local ip err.")

				resp.RespCode = "000001"
				resp.RespMsg = "project local gene fail!"
				c.JSON(http.StatusOK, resp)
				return
			}
			projectdata.IP = ip.String()
			projectdata.Project = &project.Project
			result, err := httputil.PublicProjectCrt(projectdata)
			if err != nil {
				resp.RespCode = "000006"
				resp.RespMsg = err.Error()
				c.JSON(http.StatusOK, resp)
				return
			}
			if result.RespCode != "000000" {
				resp.RespCode = result.RespCode
				resp.RespMsg = result.RespMsg
				c.JSON(http.StatusOK, resp)
				return
			}
			resp.RespCode = "000000"
			resp.RespMsg = "project local gene success!"
			c.JSON(http.StatusOK, resp)
		}
	})

	// 更新项目推送到server端
	r.POST("projectGenLocalUpdate", func(c *gin.Context) {
		var project projectmanagement.FullProject
		var resp orm.Response
		var projectdata httputil.Projectdata

		if c.Bind(&project) == nil {
			ip, err := netutil.ExternalIP()
			if err != nil {
				global.LOG.WithFields(logrus.Fields{
					"err": err,
				}).Error("get local ip err.")

				resp.RespCode = "000001"
				resp.RespMsg = "project local gene fail!"
				c.JSON(http.StatusOK, resp)
				return
			}
			projectdata.IP = ip.String()
			projectdata.Project = &project.Project
			result, err := httputil.PublicProjectCrtUpdate(projectdata)
			if err != nil {
				resp.RespCode = "000006"
				resp.RespMsg = err.Error()
				c.JSON(http.StatusOK, resp)
				return
			}
			if result.RespCode != "000000" {
				resp.RespCode = result.RespCode
				resp.RespMsg = result.RespMsg
				c.JSON(http.StatusOK, resp)
				return
			}
			resp.RespCode = "000000"
			resp.RespMsg = "project local gene success!"
			c.JSON(http.StatusOK, resp)
		}
	})

	//删除原子服务
	r.POST("deleteAtomService", func(c *gin.Context) {
		var param map[string]interface{}
		if c.Bind(&param) == nil {
			resp := atomservice.DeleteAtom(param["atomsvrid"].(string))
			c.JSON(http.StatusOK, resp)
		}
	})

	// 获取服务端的数据列表
	r.POST("getServerProjectList", func(c *gin.Context) {
		projectList, _ := projectmanagement.GetServerProjectList()
		c.JSON(http.StatusOK, projectList)
	})

	// 将server端的project项目数据同步到本地
	r.POST("pullServerProjectToLocal", func(c *gin.Context) {
		var project projectmanagement.FullProject
		var resp orm.Response
		var projectdata httputil.Projectdata

		if c.Bind(&project) == nil {
			ip, err := netutil.ExternalIP()
			if err != nil {
				global.LOG.WithFields(logrus.Fields{
					"err": err,
				}).Error("get local ip err.")

				resp.RespCode = "000001"
				resp.RespMsg = "Synchronization local gene fail!"
				c.JSON(http.StatusOK, resp)
				return
			}
			projectdata.IP = ip.String()
			projectdata.Project = &project.Project
			projectList, err := httputil.PullProjectFormServer(projectdata)
			if err != nil {
				resp.RespCode = "000005"
				resp.RespMsg = err.Error()
				c.JSON(http.StatusOK, resp)
				return
			}
			// 更新本地数据
			server, err := projectmanagement.UpdateLocalDateFromServer(projectList)
			if err != nil {
				resp.RespCode = server.RespCode
				resp.RespMsg = server.RespMsg
				c.JSON(http.StatusOK, resp)
				return
			}
			resp.RespCode = "000000"
			resp.RespMsg = "Synchronization Succeeded"
			c.JSON(http.StatusOK, resp)
		}
	})

	r.POST("copyAtomService", func(c *gin.Context) {
		var param map[string]interface{}
		if c.Bind(&param) == nil {
			resp := atomservice.CopyAtom(param)
			c.JSON(http.StatusOK, resp)
		}
	})

	// 原子服务类别列表
	r.POST("listCatagory", func(c *gin.Context) {
		resp := atomservice.ListCatagory()
		c.JSON(http.StatusOK, resp)
	})

	r.POST("listAtomService", func(c *gin.Context) {
		var param map[string]interface{}
		if c.Bind(&param) == nil {
			resp := atomservice.ListAtom(param)
			c.JSON(http.StatusOK, resp)
		}
	})

	//参数自动映射
	r.POST("autoMapping", func(c *gin.Context) {
		var param map[string]interface{}
		if c.Bind(&param) == nil {
			resp := orm.GetParamMapping1(param)
			c.JSON(http.StatusOK, resp)
		}
	})

	return r
}
